import React, { PureComponent, Fragment } from 'react';
import { connect } from 'dva';
import {
  Row,
  Col,
  Card,
  Form,
  Select,
  Button,
  message,
  Divider,
} from 'antd';
import StandardTable from '@/components/StandardTable';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import TopUp from './topUp';
import DescView from './descView';
import styles from '../UserManage.less';
import { financeMode, repayMode, repayStatus, compensatoryStatus } from '../../../common/options';
import { powerBtnFunc } from '@/utils/utils';
import * as options from '../../../common/options';

const Option = Select.Option;
const FormItem = Form.Item;

/* eslint react/no-multi-comp:0 */
@connect(({ repayModel, loading }) => ({
  repayModel,
  loading: loading.models.repayModel,
}))

@Form.create()
class DeptManage extends PureComponent {


  constructor(props) {
    super(props);
    this.state = {
      modalVisible: false,
      typeModalVisible: false,//  窗口显示类型 false 为充值
      lookDescView: false,
      status: 1,
      selectedRows: {},
      formValues: {},
      pagination: {
        pageNo: 1,
        pageSize: 15,
      },
    };

  }

  componentDidMount() {
    this.getList();
  }

  getList = () => {
    const { dispatch } = this.props;
    const { pagination, formValues, status } = this.state;

    dispatch({
      type: 'repayModel/fetch',
      payload: { ...formValues, ...pagination, status: status },
    });
  };
  handleStandardTableChange = (pagination) => {
    const { formValues } = this.state;
    this.setState({
      formValues: formValues,
      pagination: {
        pageNo: pagination.current,
        pageSize: 15,
      },
    }, () => {
      this.getList();
    });
  };
  //重置
  handleFormReset = () => {
    const { form, dispatch } = this.props;
    form.resetFields();
    this.setState({
      formValues: {},
    });
    dispatch({
      type: 'repayModel/fetch',
      payload: {},
    });
  };


  //搜索
  handleSearch = e => {
    e.preventDefault();
    const { dispatch, form } = this.props;
    form.validateFields((err, fieldsValue) => {
      if (err) return;
      const values = {
        ...fieldsValue,
      };
      this.setState({
        formValues: values,
        status: values.status,
      });
      dispatch({
        type: 'repayModel/fetch',
        payload: values,
      });
    });
  };
  //充值窗口
  handleModalVisible = (flag, record) => {
    this.setState({
      typeModalVisible: !flag,
      modalVisible: !!flag,
      selectedRows: record,
    });
  };

  //查看
  handleLookDesc = (flag, record) => {
    const { dispatch } = this.props;
    this.setState({
      lookDescView: !!flag,
      selectedRows: record,
    }, () => {
      if (!!flag) {
        dispatch({
          type: 'repayModel/getRepayDesc',
          payload: { repaymentNo: record.repaymentNo },
        });
      }
    });
  };
  //还款窗口
  handleRepay = (flag, record) => {
    this.setState({
      typeModalVisible: flag,
      modalVisible: !!flag,
      selectedRows: record,
    });
  };
  handleAdd = (type, fields) => {
    const { dispatch } = this.props;
    const { selectedRows } = this.state;
    let obj = {
      ...fields,
      repaymentNo: selectedRows.repaymentNo,
    };
    if (!type) {
      dispatch({
        type: 'repayModel/recharge',
        payload: obj,
        callback: (res) => {
          if (res.code === 200) {
            this.handleModalVisible(false, []);
            message.success(res.errMsg);
          } else {
            message.error(res.errMsg);
          }

        },
      });
    } else {
      dispatch({
        type: 'repayModel/repayment',
        payload: obj,
        callback: (res) => {
          if (res.code === 200) {
            window.open(res.msg.url);
            this.handleRepay(false, []);
          } else {
            message.error(res.errMsg);
          }

        },
      });
    }
  };


  renderSimpleForm() {
    const { form: { getFieldDecorator } } = this.props;
    const { status } = this.state;
    return (
      <Form onSubmit={this.handleSearch} layout="inline">
        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
          <Col md={6} sm={24}>
            <FormItem label="状态">
              {getFieldDecorator('status', {
                initialValue: status,
              })(
                <Select placeholder={'请选择类型'} style={{ width: '100%' }}>
                  <Option value={1}>七日内待还款</Option>
                  <Option value={2}>待还款</Option>
                  <Option value={3}>未确认</Option>
                  <Option value={4}>已还款</Option>
                </Select>,
              )}
            </FormItem>
          </Col>
          <Col md={6} sm={24}>
        <span className={styles.submitButtons}>
        <Button type="primary" htmlType="submit">
        查询
        </Button>
        <Button style={{ marginLeft: 8 }} onClick={this.handleFormReset}>
        重置
        </Button>

        </span>
          </Col>
        </Row>
      </Form>
    );
  }


  render() {
    const { repayModel: { data, repayDesc }, loading } = this.props;
    const { selectedRows, modalVisible, lookDescView, typeModalVisible } = this.state;

    const columns = [
      {
        title: '还款编号',
        dataIndex: 'repaymentNo',
      },

      {
        title: '企业名称',
        dataIndex: 'enterpriseName',
      },
      {
        title: '项目名称',
        dataIndex: 'projectName',
      },
      {
        title: '还款日期',
        dataIndex: 'repayTime',
      },
      {
        title: '回款日期',
        dataIndex: 'backTime',
      },
      {
        title: '账单金额',
        dataIndex: 'amount',
      },
      {
        title: '应还本金',
        dataIndex: 'principal',
      },
      {
        title: '应还利息',
        dataIndex: 'interest',
      },
      {
        title: '服务费',
        dataIndex: 'fee',
      },

      {
        title: '状态',
        dataIndex: 'status',
        render: val => <span>{options.repayStatus.map(item => (item.key === val ? item.value : ''))}</span>,
      },
      {
        title: '操作',
        render: (text, record) => (
          <Fragment>
            {
              powerBtnFunc('100102', [<a onClick={() => this.handleRepay(true, record)}>还款</a>,
                <Divider type="vertical"/>])
            }
            {
              powerBtnFunc('100103',
                [<a onClick={() => this.handleLookDesc(true, record)}>查看</a>,
                  <Divider type="vertical"/>],
              )}
            <a onClick={() => this.handleModalVisible(true, record)}>充值</a>
          </Fragment>
        ),
      },
    ];


    return (
      <PageHeaderWrapper title="商户还款管理">
        <Card bordered={false}>
          <div className={styles.tableList}>
            <div className={styles.tableListForm}>{this.renderSimpleForm()}</div>
            <StandardTable
              selectedRows={selectedRows}
              loading={loading}
              data={data}
              rowKey={'repaymentNo'}
              columns={columns}
              rowSelectHide={true}
              onChange={this.handleStandardTableChange}
            />
          </div>
        </Card>
        {!loading
          ?
          <DescView
            handleLookDesc={this.handleLookDesc}
            selectedRows={repayDesc}
            lookDescView={lookDescView}/>
          :
          ''}
        <TopUp
          selectedRows={selectedRows}
          handleAdd={this.handleAdd}
          handleModalVisible={this.handleModalVisible}
          modalVisible={modalVisible}
          typeModalVisible={typeModalVisible}
        />

      </PageHeaderWrapper>
    );
  }
}

export default DeptManage;
